package com.dudu.access;

import java.util.Calendar;
import java.util.UUID;

import net.sf.json.JSONObject;

import org.apache.commons.lang.StringUtils;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;

import com.dudu.utils.DateUtils;
import com.dudu.utils.DictionaryUtils;
import com.dudu.utils.HttpRequest;
import com.dudu.bean.DialResultBean;
import com.dudu.enumeration.RemindEnum;
import com.dudu.service.ILogService;
import com.dudu.service.impl.LogService;

/**
 * 承启通通道Util
 * 
 * @author gaoxs
 * 
 */
public class ChengQiUtil {
    private static ILogService logService = new LogService();
    private static String serviceUrl = DictionaryUtils.getValueByTypeAndKey("ChengQi", "serviceUrl");
    private static String vccId = DictionaryUtils.getValueByTypeAndKey("ChengQi", "vccId");
    private static String serviceUrl_95=DictionaryUtils.getValueByTypeAndKey("ChengQi", "serviceUrl_95");
    private static String vccId_95 = DictionaryUtils.getValueByTypeAndKey("ChengQi", "vccId_95");
    // private static String serviceUrl = "http://153.3.49.41:8078";
   // private static String vccId = "2004";

    
    /**
     * 结束通话
     * 
     * @param sessionId
     * @return
     */
    public static JSONObject dialStop(String sessionId, String displayNum) {
	JSONObject object = new JSONObject();
	// 拼接请求包体
	String requsetbody = "";
	String desc = "";
	String vccIdStr="";
	if(displayNum.startsWith("950786")){
	    vccIdStr=vccId_95;
	}else{
	    vccIdStr=vccId;
	}
	StringBuilder sb = new StringBuilder("<?xml version='1.0' encoding='utf-8'?>");
	// callRequest，双向呼叫申请；IVRRequest，单向呼叫申请
	sb.append("<callOutService version='1.0'><service name='cancelRequest'>");
	sb.append("<messageID>").append(UUID.randomUUID().toString()).append("</messageID>");// 呼叫申请流水号唯一
	sb.append("<callID>").append(sessionId).append("</callID>");
	sb.append("<vccID>").append(vccIdStr).append("</vccID>");// 企业ID（测试使用2004，商用待定
	sb.append("</service></callOutService>");
	requsetbody = sb.toString();
	String url = serviceUrl;
	if(vccId.equals("2004")){
	    url=url + "/CQTTest/callBack/cancelDial.do";
	}
	
	long begin = Calendar.getInstance().getTimeInMillis();
	String response = HttpRequest.postXml(url, requsetbody);
	long end = Calendar.getInstance().getTimeInMillis();
	String result = "";
	if (StringUtils.isNotBlank(response)) {
	    try {
		Document doc = DocumentHelper.parseText(response);
		Element root = doc.getRootElement();
		Element service = root.element("service");
		result = service.elementTextTrim("result");
		if (result.equals("1000")) {
		    result = "0";
		    desc = "OK";
		} else {
		    result = "-1";
		    desc = service.elementTextTrim("reason");
		}
	    } catch (DocumentException e) {
		e.printStackTrace();
	    }
	} else {
	    result = "-1";
	    response = "";
	    desc = "接口响应为空";
	}
	double time = Double.valueOf((end - begin)) / 1000;
	logService.logIms(time, "DailStop", "【" + requsetbody.toString() + "】", "【" + response + "】", result, DateUtils.getCurrentTime(), "ChengQi", "");
	object.put("result", result);
	object.put("discripe", desc);
	return object;
    }
    /**
     * 点击拨号、两方通话
     * @param caller  主叫
     * @param called  被叫
     * @param displayNum  显号
     * @param needRecord 是否录音：0表示不录音；1表示录音；默认值0
     * @return
     */
    public static DialResultBean dial(String caller, String called, String displayNum, String needRecord) {
	DialResultBean resultBean = new DialResultBean();

	// 拼接请求包体
	String requsetbody = "";
	String desc = "";
	String url = "";
	String vccIdStr="";
	if(displayNum.startsWith("950786")){
	    url=serviceUrl_95;
	    vccIdStr=vccId_95;
	}else{
	    url=serviceUrl;
	    vccIdStr=vccId;
	}
	StringBuilder sb = new StringBuilder("<?xml version='1.0' encoding='utf-8'?>");
	// callRequest，双向呼叫申请；IVRRequest，单向呼叫申请
	sb.append("<callOutService version='1.0'><service name='callRequest'>");
	sb.append("<messageID>").append(UUID.randomUUID().toString()).append("</messageID>");// 呼叫申请流水号唯一
	// 主叫电话（0086+手机号码，如是固话则去除区号的0；例如：008618060475543））
	sb.append("<callingNumber>").append(replacephone(caller)).append("</callingNumber>");
	// 被叫电话（0086+手机号码，如是固话则去除区号的0；例如：008618060475543）
	sb.append("<calledNumber>").append(replacephone(called)).append("</calledNumber>");
	sb.append("<callerAreaID>").append("").append("</callerAreaID>");// 地区ID
	sb.append("<callerDisplayNum>").append(replacephone(displayNum)).append("</callerDisplayNum>");// 主叫显号
	sb.append("<calledDisplayNum>").append(replacephone(displayNum)).append("</calledDisplayNum>");// 被叫显号
	sb.append("<vccID>").append(vccIdStr).append("</vccID>");// 企业ID（测试使用2004，商用待定
	// 计费号码，默认被叫来显例如：02557914526
	sb.append("<chargeNumber>").append(displayNum).append("</chargeNumber>");// 显号
	sb.append("<isRecord>").append(needRecord).append("</isRecord>");// 是否录音，0：不录音；1：混音方式录音
	sb.append("</service></callOutService>");
	requsetbody = sb.toString();
	if(vccId.equals("2004")){
	    url=url + "/CQTTest/callBack/dial.do";
	}
	long begin = Calendar.getInstance().getTimeInMillis();
	String response = HttpRequest.postXml(url, requsetbody);
	remind(response, RemindEnum.OPEN_DIAL_CHENGQI.getKey(),RemindEnum.OPEN_DIAL_CHENGQI.getValue());
	long end = Calendar.getInstance().getTimeInMillis();
	String result = "";
	String sessionid = "";
	if (StringUtils.isNotBlank(response)) {
	    try {
		Document doc = DocumentHelper.parseText(response);
		Element root = doc.getRootElement();
		Element service = root.element("service");
		result = service.elementTextTrim("result");
		if (result.equals("1000")) {
		    sessionid = service.elementTextTrim("callID");
		    result = "0";
		    desc = "OK";
		} else {
		    result = "-1";
		    desc = service.elementTextTrim("reason");
		}
	    } catch (DocumentException e) {
		e.printStackTrace();
	    }
	} else {
	    result = "-1";
	    response = "";
	    desc = "接口响应为空";
	}
	double time = Double.valueOf((end - begin)) / 1000;
	logService.logIms(time, "Dial", "【" + requsetbody.toString() + "】", "【" + response + "】", result, DateUtils.getCurrentTime(), "ChengQi", caller);

	resultBean.setDisplayNbr(displayNum);
	resultBean.setResult(result);
	resultBean.setSessionId(sessionid);
	resultBean.setDesc(desc);
	return resultBean;
    }
    /**
     * 提醒
     * 
     * @param response
     * @param abilityType
     * @throws DocumentException
     */
    public static void remind(String response, String abilityType, String content) {
	if (StringUtils.isNotBlank(response)) {

	    try {
		Document doc = DocumentHelper.parseText(response);
		Element root = doc.getRootElement();
		Element service = root.element("service");
		String result = service.elementTextTrim("result");
		if (StringUtils.isBlank(result)) {// 返回无状态码与错误信息
		    RemindUtils.remind(abilityType, content + ":" + response, "sms");
		} else if (result.equals("1006")) {// 显号不对
		    RemindUtils.remind(abilityType, content + ":" + "显号为空或者错误", "sms");
		}else if(result.equals("1000")){//1000成功
		    
		}else{
		    //RemindUtils.remind(abilityType, content + ":" + service.elementTextTrim("reason"), "email2");
		}
	    } catch (DocumentException e) {
		RemindUtils.remind(abilityType, content + ":" + response, "sms");
	    }

	} else {
	    RemindUtils.remind(abilityType, content + ":接口响应为空", "sms");
	}
    }
    private static String replacephone(String phone) {
	if (phone.startsWith("0")) {
	    phone = phone.substring(1);
	}
	return "0086" + phone;
    }
    public static void main(String[] args) {
	DialResultBean bean=ChengQiUtil.dial("17001090120", "17001090122", "02557914526", "1");
	//System.out.println(bean.getSessionId());
	//ChengQiUtil.dialStop("C20170306184634AC102A3D1000263550");
    }

}
